import * as Cesium from "cesium";

// 注意：确保viewer在当前模块可访问（若在其他模块定义，需传入或导出）
// 示例：假设viewer在入口文件中创建并导出，此处导入
// import { viewer } from './main'; // 根据实际路径调整

// 若viewer在当前模块创建，需补充：
// const viewer = new Cesium.Viewer("cesiumContainer", {
//     terrainProvider: Cesium.createWorldTerrain()
// });

// 雷达位置（示例：北京附近）
const radarPosition = Cesium.Cartesian3.fromDegrees(116.39, 39.91, 500);

// 生成干扰包络的基础参数
const params = {
    radius: 5000,
    thetaRange: Math.PI * 1.5,
    phiRange: Math.PI / 4,
    vertexCount: 50,
    heightSegments: 10,
    noiseIntensity: 300,
    updateSpeed: 0.05
};

// 生成带扰动的圆锥面几何体
function generateJammingGeometry() {
    const positions = [];
    const indices = [];
    let index = 0;
    // 显式指定椭球体（WGS84）
    const ellipsoid = Cesium.Ellipsoid.WGS84;

    for (let i = 0; i <= params.heightSegments; i++) {
        // 关键：避免heightRatio=0导致顶点与雷达位置完全重合（加微小偏移）
        const heightRatio = Math.max(i / params.heightSegments, 0.001);
        const currentRadius = params.radius * heightRatio;

        for (let j = 0; j < params.vertexCount; j++) {
            const theta = (j / params.vertexCount) * params.thetaRange - params.thetaRange / 2;
            const phi = (Math.random() - 0.5) * params.phiRange;

            // 随机扰动
            const noiseX = (Math.random() - 0.5) * params.noiseIntensity * heightRatio;
            const noiseY = (Math.random() - 0.5) * params.noiseIntensity * heightRatio;
            const noiseZ = (Math.random() - 0.5) * params.noiseIntensity * heightRatio;

            // 极坐标转笛卡尔坐标（相对雷达）
            const x = currentRadius * Math.cos(phi) * Math.sin(theta) + noiseX;
            const y = currentRadius * Math.sin(phi) + noiseY;
            const z = currentRadius * Math.cos(phi) * Math.cos(theta) + noiseZ;

            // 转换为世界坐标（确保不会出现(0,0,0)）
            const localPosition = new Cesium.Cartesian3(x, y, z);
            const worldPosition = Cesium.Cartesian3.add(radarPosition, localPosition, new Cesium.Cartesian3());
            positions.push(worldPosition);

            // 生成三角形索引（避免越界）
            if (i > 0 && j > 0) {
                const prevIndex = index - params.vertexCount;
                // 检查索引有效性（防止负数或越界）
                if (prevIndex - 1 >= 0 && index - 1 >= 0) {
                    indices.push(prevIndex - 1, prevIndex, index - 1);
                    indices.push(prevIndex, index, index - 1);
                }
            }
            index++;
        }
    }

    // 创建几何体（添加椭球体和边界球）
    return new Cesium.Geometry({
        attributes: {
            position: new Cesium.GeometryAttribute({
                componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                componentsPerAttribute: 3,
                values: new Float64Array(Cesium.Cartesian3.packArray(positions))
            }),
            positionMC: new Cesium.GeometryAttribute({
                componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                componentsPerAttribute: 3,
                values: new Float64Array(Cesium.Cartesian3.packArray(
                    positions.map(pos => Cesium.Cartesian3.subtract(pos, radarPosition, new Cesium.Cartesian3()))
                ))
            })
        },
        indices: new Uint32Array(indices),
        boundingSphere: Cesium.BoundingSphere.fromPoints(positions),
        workerName: "createCustomGeometry",
        ellipsoid: ellipsoid // 显式关联椭球体
    });
}

// 自定义干扰材质（修复着色器变量传递）
const jammingMaterial = new Cesium.Material({
    fabric: {
        type: "JammingMaterial",
        uniforms: {
            color1: new Cesium.Color(1.0, 0.2, 0.2, 0.3),
            color2: new Cesium.Color(1.0, 0.8, 0.2, 0.1),
            noiseScale: 0.001,
            time: 0,
            radius: params.radius
        },
        source: `
      #version 300 es
      precision highp float;

      // 顶点着色器：从几何体属性获取模型空间位置
      in vec3 positionMC; // 对应几何体的positionMC属性
      out vec3 v_positionMC; // 传递给片段着色器

      void czm_vertexMain() {
        v_positionMC = positionMC; // 传递模型空间位置
        gl_Position = czm_modelViewProjection * vec4(position, 1.0); // 使用世界坐标position
      }

      // 噪声函数
      float noise(vec2 p) {
        return fract(sin(dot(p, vec2(12.9898,78.233))) * 43758.5453);
      }

      // 片段着色器接收
      in vec3 v_positionMC;

      czm_material czm_getMaterial(czm_materialInput materialInput) {
        czm_material material = czm_getDefaultMaterial(materialInput);
        float distance = length(v_positionMC) / radius;
        vec4 color = mix(color1, color2, distance);
        float n = noise(v_positionMC.xy * noiseScale + time);
        color.rgb += (n - 0.5) * 0.2;
        material.diffuse = color.rgb;
        material.alpha = color.a;
        return material;
      }
    `
    }
});

// 创建并更新Primitive
let jammingPrimitive;
export function updateJammingGeometry() {
    const geometry = generateJammingGeometry();
    if (jammingPrimitive) {
        viewer.scene.primitives.remove(jammingPrimitive);
    }
    jammingPrimitive = new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: geometry
        }),
        appearance: new Cesium.MaterialAppearance({
            material: jammingMaterial,
            translucent: true,
            // 声明需要传递给着色器的属性（关键）
            vertexShaderSource: jammingMaterial.shaderSource.vertexShaderSource,
            fragmentShaderSource: jammingMaterial.shaderSource.fragmentShaderSource,
            attributeLocations: {
                position: Cesium.VertexAttributeSemantic.POSITION, // 世界坐标
                positionMC: 1 // 模型空间坐标（自定义属性位置）
            }
        }),
        asynchronous: false
    });
    viewer.scene.primitives.add(jammingPrimitive);

    // 更新材质时间动画
    jammingMaterial.uniforms.time += params.updateSpeed;
    requestAnimationFrame(updateJammingGeometry);
}

// updateJammingGeometry();